<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Enums\LotteryRecordStatus;
use App\Exports\LotteryRecordExport;
use App\Http\Controllers\Controller;
use App\Jobs\DownloadsJob;
use App\Models\AgentUser;
use App\Models\Download;
use App\Models\Lottery;
use App\Models\LotteryRecord;
use App\Utils\UploadHelper;
use Illuminate\Support\Arr;
use Vinlon\Laravel\LayAdmin\Exceptions\AdminException;

class LotteryRecordController extends Controller
{
    public function index()
    {
        $lotteryId = request()->lottery_id;
        $query = LotteryRecord::query()
            ->with(['user', 'award'])
            ->where('lottery_id', $lotteryId)
            ->when(request()->award_id, function ($q) {
                return $q->where('award_id', request()->award_id);
            })
            ->when(request()->keyword, function ($q) {
                return $q->whereHas('user', function ($q1) {
                    return $q1->where('mobile', 'like', '%' . request()->keyword . '%');
                });
            })->orderByDesc('id');

        return paginate_result($query, function (LotteryRecord $record) {
            $record->remark = json_decode($record->remark);

            return $record;
        });
    }

    public function deliver($recordId)
    {
        $params = request()->validate([
            'express_no' => 'nullable',
            'express_name' => 'nullable',
        ]);
        /** @var LotteryRecord $record */
        $record = LotteryRecord::query()->find($recordId);
        $expressNo = request()->express_no;
        $expressName = request()->express_name;
        if (empty($expressNo) && empty($expressName)) {
            $record->remark = json_encode($params);
            $record->status = LotteryRecordStatus::WAITING;
        } elseif (empty($expressNo) || empty($expressName)) {
            throw new AdminException('快递名称和单号必须同时输入');
        } else {
            $record->remark = json_encode($params);
            $record->status = LotteryRecordStatus::SENT;
        }
        $record->save();
    }

    /** 导出中奖记录 */
    public function exportRecords()
    {
        $params = request()->validate([
            'award_id' => 'required',
            'lottery_id' => 'required',
        ]);
        /** @var AgentUser $agentUser */
        $agentUser = auth()->user();
        $lottery = Lottery::query()->where('agent_id', $agentUser->agent_id)->find(request()->lottery_id);
        $award = $lottery->awards()->find(request()->award_id);

        $file = '[' . $award->name . ']中奖记录导出' . date('YmdHis') . '.xls';
        $download = Download::create([
            'agent_id' => $agentUser->agent_id,
            'user_id' => $agentUser->id,
            'name' => $file,
            'url' => 'storage/' . $file,
            'status' => 0,
            'model' => LotteryRecordExport::class,
            'request' => json_encode($params),
        ]);

        dispatch(new DownloadsJob($download));
    }

    /** 批量更新发货信息 */
    public function batchUpdateDelivery($lotteryId)
    {
        $data = UploadHelper::readExcel(request()->file('file'));
        // 检查文件头和是否有数据
        $header = array_slice($data[0], 0, 10);
        unset($data[0]);
        if ($header != ['ID', '奖品名称', '中奖用户', '中奖时间', '发放状态', '收货手机号', '收货姓名', '收货地址地址', '快递名称(可编辑)', '快递单号(可编辑)']) {
            throw new AdminException('文件头错误，请直接修改导出的文件后上传');
        }
        if (0 == count($data)) {
            throw new AdminException('文件中不包含数据');
        }
        if (count($data) > 2000) {
            throw new AdminException('每次最多上传2000人');
        }
        /** @var Lottery $lottery */
        $lottery = Lottery::query()->find($lotteryId);
        if (!$lottery) {
            throw new AdminException('无效的活动ID');
        }
        foreach ($data as $row) {
            $recordId = Arr::get($row, 0);
            $expressName = Arr::get($row, 8);
            $expressNo = Arr::get($row, 9);
            /** @var LotteryRecord $record */
            $record = LotteryRecord::query()->where('lottery_id', $lotteryId)->find($recordId);
            $record->remark = ['express_no' => $expressNo, 'express_name' => $expressName];
            if (empty($expressName) && empty($expressNo)) {
                $record->status = LotteryRecordStatus::WAITING;
            } else {
                $record->status = LotteryRecordStatus::SENT;
            }
            $record->save();
        }
    }
}
